import 'dart:async';

import 'package:flutter/material.dart';
import 'package:happy_elf_app/apis/home.dart';
import 'package:happy_elf_app/store/config.dart';
import 'package:happy_elf_app/store/home.dart';
import 'package:happy_elf_app/utils/adaption.dart';
import 'package:happy_elf_app/utils/color.dart';
import 'package:happy_elf_app/utils/globalKey.dart';
import 'package:happy_elf_app/widgets/Toast/index.dart';
import 'package:sensors_plus/sensors_plus.dart';

class Enter extends StatefulWidget {
  final Function callBack;
  const Enter({super.key, required this.callBack});

  @override
  State<Enter> createState() => _EnterState();
}

class _EnterState extends State<Enter> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  //是否已经显示摇一摇弹窗
  bool isShow = false;

  final _streamSubscriptions = <StreamSubscription<dynamic>>[];

  bool isrefreshing = true; //是否正在刷新
  Map lotteryData = {}; //抽签结果数据
  final HomeDataProvider = Provider.of<HomeData>(
    Global.navigatorKey.currentContext!,
    listen: false,
  );

  @override
  void initState() {
    super.initState();
    shakeListen();
    _controller = AnimationController(vsync: this);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
    //取消监听
    for (final subscription in _streamSubscriptions) {
      subscription.cancel();
    }
  }

  shakeListen() {
    _streamSubscriptions.add(
        userAccelerometerEvents.listen((UserAccelerometerEvent event) async {
      //不受重力的影响
      // print("event的值${event}");
      if (isShow) return;
      if (HomeDataProvider.target['content'] == null) {
        Toast.show(context: context, message: '请先设定目标');
        return;
      }
      int value = 4;
      if (event.x >= value ||
          event.x <= -value ||
          event.y >= value ||
          event.y <= -value ||
          event.z >= value ||
          event.z <= -value) {
        print("已摇了-----$isShow");
        if (isShow == false) {
          setState(() {
            isShow = true;
          });
          var res = await Home().getLottery();
          if (res['code'] == 200) {
            print("抽签结果${res['data']}");
            lotteryData = res['data'];
            //延时两秒匹配到用户
            Future.delayed(const Duration(seconds: 1), () {
              print("跳出弹窗");
              showTaskDialog();
            });
          }
        }
      }
    }));
  }

  void showTaskDialog() {
    final String verticalText = '恭 喜 获 得'.split('').join('\n');
    final String signTxet = lotteryData['content'].split('').join('\n');
    final String upTxet = '上上签'.split('').join('\n');
    showDialog(
      context: Global.navigatorKey.currentContext!,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20.0),
          ),
          content: SizedBox(
            width: 287,
            height: 600,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Container(
                      width: 30.px,
                      // height: 200,
                      alignment: Alignment.center,
                      child: Text(
                        verticalText,
                        softWrap: true,
                        textAlign: TextAlign.center,
                        textDirection: TextDirection.rtl,
                        style: const TextStyle(
                            fontSize: 20,
                            fontWeight: FontWeight.w400,
                            height: 1.5),
                      ),
                    ),
                    SizedBox(width: 40),
                    Stack(
                      children: [
                        Image.asset(
                          'lib/assets/images/home/Union.png',
                          width: 150,
                          height: 500,
                        ),
                        Positioned(
                          top: 40,
                          left: 0,
                          right: 6,
                          child: Column(
                            children: [
                              Text(
                                upTxet,
                                softWrap: true,
                                textAlign: TextAlign.center,
                                style: const TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.w400,
                                    height: 1.5),
                              ),
                              SizedBox(height: 30),
                              Container(
                                padding: EdgeInsets.symmetric(
                                    horizontal: 8.px, vertical: 38.px),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(20),
                                  border: Border.all(
                                      width: 1.px, color: hexColor('#333333')),
                                ),
                                child: Text(
                                  signTxet,
                                  softWrap: true,
                                  textAlign: TextAlign.center,
                                  style: const TextStyle(
                                      fontSize: 18,
                                      fontWeight: FontWeight.w400,
                                      height: 1.5),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
                const Spacer(),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    GestureDetector(
                      child: Container(
                        padding: EdgeInsets.symmetric(
                            horizontal: 12.px, vertical: 5.px),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(4),
                            border: Border.all(
                                width: 1.px, color: hexColor('#345634'))),
                        child: Text(
                          '重新抽取',
                          style: TextStyle(color: hexColor('#345345')),
                        ),
                      ),
                      onTap: () async {
                        Navigator.of(context).pop(); // 先关闭当前弹窗
                        isShow = false;
                        isrefreshing = true;
                        if (HomeDataProvider.target['content'] == null) {
                          Toast.show(context: context, message: '请先设定目标');
                          return;
                        }
                        if (isShow == false) {
                          setState(() {
                            isShow = true;
                          });
                          var res = await Home().getLottery();
                          if (res['code'] == 200) {
                            print("抽签结果${res['data']}");
                            lotteryData = res['data'];
                            //延时两秒匹配到用户
                            Future.delayed(const Duration(seconds: 1), () {
                              print("跳出弹窗");
                              isrefreshing = false;
                              showTaskDialog();
                            });
                          }
                        }
                      },
                    ),
                    const SizedBox(width: 20),
                    ElevatedButton(
                      onPressed: () async {
                        isShow = false;
                        // 接口确定目标
                        // HomeDataProvider.target
                        Map data = {
                          'targetContentId': HomeDataProvider.target['id'],
                          'targetName': HomeDataProvider.target['content']
                        };
                        var res = await Home().submitTarget(data);
                        if (res['code'] == 200) {
                          Navigator.of(context).pop();
                          widget.callBack(res['data']);
                        }
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: hexColor('E9614D'),
                      ),
                      child: const Text('   确定   '),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          !isrefreshing
              ? const Image(
                  image: AssetImage("lib/assets/animate/task.gif"), // 播放中的 GIF
                  gaplessPlayback: true, // 切换时无闪烁（关键）
                  width: 390,
                )
              : Image.asset(
                  'lib/assets/images/home/bucket.png',
                  height: 520,
                ),
          Container(
            width: 168,
            alignment: Alignment.center,
            margin: EdgeInsets.only(top: 16),
            child: Row(
              children: [
                GestureDetector(
                  child: Image.asset('lib/assets/images/home/update.png',
                      width: 60, height: 60),
                  onTap: () {
                    setState(() {
                      isrefreshing = false;
                    });
                    // 倒计时3秒后停止
                    Future.delayed(const Duration(seconds: 3), () {
                      setState(() {
                        isrefreshing = true;
                      });
                    });
                  },
                ),
                SizedBox(width: 48),
                GestureDetector(
                  child: Image.asset('lib/assets/images/home/shake.png',
                      width: 60, height: 60),
                  onTap: () async {
                    // showTaskDialog();
                    if (HomeDataProvider.target['content'] == null) {
                      Toast.show(context: context, message: '请先设定目标');
                      return;
                    }
                    if (isShow == false) {
                      setState(() {
                        isShow = true;
                      });
                      var res = await Home().getLottery();
                      if (res['code'] == 200) {
                        print("抽签结果${res['data']}");
                        lotteryData = res['data'];
                        //延时两秒匹配到用户
                        Future.delayed(const Duration(seconds: 1), () {
                          print("跳出弹窗");
                          showTaskDialog();
                        });
                      }
                    }
                  },
                )
              ],
            ),
          ),
          Container(
            width: 300,
            alignment: Alignment.center,
            margin: EdgeInsets.only(top: 16),
            padding: EdgeInsets.symmetric(vertical: 10, horizontal: 16),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(24),
                border: Border.all(width: 1.px, color: hexColor('#cccccc'))),
            child: Text(HomeDataProvider.target['content'] ?? ''),
          )
        ],
      ),
    );
  }
}
